package net.keebook.webapp.bean;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.Messages;

@ManagedBean
@RequestScoped
public class DeleteAccountBean {
	private Boolean confirmed;
	private SessionModel sessionModel;
	@Inject
	private UserDao userDao;

	@PostConstruct
	public void init() throws IOException {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
	}
	
	public void deleteAccount() throws IOException {
		User user = getUserDao().get(getSessionModel().getUserId());
		getUserDao().delete(user);
		
		Cookie cookie = new Cookie("authKey", "");
		cookie.setMaxAge(0);
		HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
		response.addCookie(cookie);
		
		getSessionModel().clear();
		
		// Manual redirect required due to bug in Tomcat (cannot set cookie and send redirect in one response)
		// See http://www.jguru.com/faq/view.jsp?EID=53251
		response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", "login.xhtml?msg="+Messages.ACCOUNT_DELETED);
	}
	
	public Boolean getConfirmed() {
		return confirmed;
	}

	public void setConfirmed(Boolean confirmed) {
		this.confirmed = confirmed;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
